package so.sao.code.service.domain.handler;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import so.sao.code.service.domain.entity.EnterpriseInfo;
import so.sao.code.service.domain.entity.LookupTable;
import so.sao.code.service.domain.entity.RangeActivation;
import so.sao.code.service.domain.entity.TagBatch;
import so.sao.code.service.domain.entity.TagOperationLog;
import so.sao.code.service.domain.event.TagBatchCreateEvent;
import so.sao.code.service.infrastructure.SessionContext;
import so.sao.code.service.infrastructure.enums.TAG_BATCH_TYPE;
import so.sao.code.service.infrastructure.enums.TagRangeStatus;
import so.sao.code.service.infrastructure.utils.RangeUtil;
import so.sao.code.service.repository.EnterpriseInfoDao;
import so.sao.code.service.repository.LookupTableDao;
import so.sao.code.service.repository.RangeActivationDao;
import so.sao.code.service.repository.TagOperationLogDao;
import so.sao.data.dto.response.EnterpriseDTO;
import so.sao.data.feign.client.EnterpriseClient;
import so.sao.etrace.feign.client.TagBatchFeignClient;
import so.sao.etrace.model.dto.marketing.TagBatchSynchDTO;
import so.sao.sso.feign.dto.UserDTO;

/**
 * Created by Administrator on 2017/9/8.
 */
@Component
public class TagBatchCreateHandler {
	@Autowired
	RangeActivationDao rangeActivationDao;
	@Autowired
	private LookupTableDao lookupTableDao;
	@Autowired
	SessionContext context;
	@Autowired
	TagOperationLogDao tagOperationLogDao;

	@Autowired
	EnterpriseInfoDao enterpriseInfoDao;
	@Autowired
	TagBatchFeignClient  tagBatchFeignClient;
	@Autowired
	EnterpriseClient enterpriseClient;

	// @EventListener
	@TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
	public void handleLookUpTableCount(TagBatchCreateEvent event) {
		List<TagBatch> tagBatchs = event.getTagBatchs();
		LookupTable lookupTable = event.getLookupTable();
		lookupTable.setCurrentCount(
				tagBatchs.stream().mapToLong(item -> item.getTagCount()).sum() + lookupTable.getCurrentCount());
		lookupTableDao.save(lookupTable);
	}

	@EventListener
	@Async
	public void handleRollTagBatch(TagBatchCreateEvent event) {
		List<TagBatch> tagBatchs = event.getTagBatchs();
		List<RangeActivation> rangeActivations = new ArrayList<>();
		tagBatchs.forEach(tagBatch -> {
			if (tagBatch.getType() == TAG_BATCH_TYPE.ROLL) {
				RangeUtil.rangeSplit(tagBatch.getSeqnumStart(), tagBatch.getSeqnumEnd(), tagBatch.getUnitCount())
						.forEach(roll -> {
							rangeActivations.add(new RangeActivation(tagBatch.getId(), roll.getLeft(), roll.getRight(),
									tagBatch.getEseId(), TagRangeStatus.UNACTIVATE.getValue()));
						});
				rangeActivationDao.save(rangeActivations);
			}
		});
	}

	@Async
	@EventListener
	public void modifyCreatedCount(TagBatchCreateEvent event) {
		Long count = event.getTagBatchs().stream().mapToLong(item -> item.getTagCount()).sum();
		EnterpriseInfo enterpriseInfo = enterpriseInfoDao.findByEseId(event.getTagBatchs().get(0).getEseId());
		enterpriseInfo.setCreatedCount(enterpriseInfo.getCreatedCount() + count);
		enterpriseInfo.setUpCount(enterpriseInfo.getUpCount() - count);
		enterpriseInfoDao.save(enterpriseInfo);
	}

	@EventListener
	@Async
	public void logAction(TagBatchCreateEvent event) {
		UserDTO user = context.CURRECT_USER;
		List<TagBatch> tagBatchs = event.getTagBatchs();
		String action = event.getOperation().getName();
		List<TagOperationLog> logs = new ArrayList<>();
		tagBatchs.forEach(tagBatch -> {
			TagOperationLog log = new TagOperationLog(tagBatch.getId(), "管理端", action,
					tagBatch.getSeqnumStart() + "-" + tagBatch.getSeqnumEnd(), user.getUsername());
			logs.add(log);
		});
		tagOperationLogDao.save(logs);
	}
	@EventListener(condition = "#event.tagBatchs.get(0).type.getValue().equals(6)"/** 6为第三发码*/)
    public void pushEtrace(TagBatchCreateEvent event) throws Exception {
		EnterpriseDTO enterpriseDTO = enterpriseClient.findById(event.getTagBatchs().get(0).getEseId());
        List<TagBatch> tagBatches = event.getTagBatchs();
        for (TagBatch tagBatch : tagBatches) {
            TagBatchSynchDTO dto = new TagBatchSynchDTO();
            dto.setBatchBegin(tagBatch.getSeqnumStart());
            dto.setBatchEnd(tagBatch.getSeqnumEnd());
            dto.setBatchId(tagBatch.getId());
            dto.setDomain(tagBatch.getDomain());
            dto.setSubDomain(tagBatch.getSubDomain());
            dto.setEseCode(enterpriseDTO.getCode());
            dto.setEseId(tagBatch.getEseId());
			tagBatchFeignClient.tagBatchSynch(dto);
        }
    }
}
